package com.jiumi.baseconfig.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import com.jiumi.baseconfig.domain.*;
import com.jiumi.baseconfig.mapper.BaseContractLogMapper;
import com.jiumi.baseconfig.mapper.BaseOrderMapper;
import com.jiumi.baseconfig.service.*;
import com.jiumi.common.core.domain.AjaxResult;
import com.jiumi.common.utils.DateUtils;
import com.jiumi.common.utils.StringUtils;
import com.jiumi.common.utils.uuid.IdUtils;
import com.jiumi.common.utils.uuid.Seq;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jiumi.baseconfig.mapper.BaseContractMapper;
import org.springframework.transaction.annotation.Transactional;

/**
 * 合同管理Service业务层处理
 *
 * @author jiumi
 * @date 2022-12-05
 */
@Service
public class BaseContractServiceImpl implements IBaseContractService
{
    @Autowired
    private BaseContractMapper baseContractMapper;

    @Autowired
    private BaseOrderMapper baseOrderMapper;

    @Autowired
    private IBaseContractLogService baseContractLogService;

    @Autowired
    private IBaseScoreConfigService baseScoreConfigService;

    @Autowired
    private IBaseUserService userService;

    @Autowired
    private IScoreHistoryService scoreHistoryService;

    @Autowired
    private IBaseCompanyService baseCompanyService;

    @Autowired
    private IBaseCompanyAccountService baseCompanyAccountService;
    /**
     * 查询合同管理
     *
     * @param id 合同管理主键
     * @return 合同管理
     */
    @Override
    public BaseContract selectBaseContractById(Long id)
    {
        return baseContractMapper.selectBaseContractById(id);
    }


    @Override
    public BaseContract selectBaseContractByCode(String code)
    {
        return baseContractMapper.selectBaseContractByCode(code);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult confirmSignContract(BaseContract baseContract, BaseUser currentUser) {
        BaseContract contract=this.selectBaseContractById(baseContract.getId());
        if(!"03".equals(contract.getStatus())){
            return AjaxResult.error("合同状态不能进行确认");
        }
        if(contract.getCcompanyId().intValue()!=currentUser.getCompanyId().intValue()){
            return AjaxResult.error("您不是丙方用户");
        }
        BaseCompanyAccount accountParam=new BaseCompanyAccount();
        accountParam.setCompanyId(currentUser.getCompanyId());
        accountParam.setUserId(currentUser.getUserId());
        List<BaseCompanyAccount> accountList= baseCompanyAccountService.selectBaseCompanyAccountList(accountParam);
        if(accountList.size()==0){
            return AjaxResult.error("只有公司管理员才能确认合同");
        }
        BaseCompanyAccount userAccount=accountList.get(0);
        if(!"Y".equalsIgnoreCase(userAccount.getIsMain())){
            return AjaxResult.error("只有公司管理员才能确认合同");
        }
        BaseCompany contractCompany=baseCompanyService.selectBaseCompanyById(contract.getCcompanyId());
        if(StringUtils.isEmpty(contractCompany.getSealUrl())){
            return AjaxResult.error("请先上传公司公章");
        }
        try{
            baseContract.setConfirmUserId(currentUser.getUserId());
            baseContract.setConfirmTime(DateUtils.getNowDate());
            baseContract.setConfirmsealUrl(contractCompany.getSealUrl());
            baseContract.setUpdateBy(currentUser.getUserName());
            baseContract.setStatus("04");
            int result= this.updateBaseContract(baseContract);
            //家政协议三方
            /*if("02".equals(contract.getCategoryType())){
                if("01".equals(contract.getSignType())){
                    BaseOrder order=new BaseOrder();
                    order.setContractCode(contract.getContractCode());
                    order.setTitle("服务费");
                    order.setCompanyId(contract.getCcompanyId());
                    order.setCompanyName(contract.getCcompanyName());
                    order.setContractCode(contract.getContractCode());
                    order.setOrderAmount(contract.getServiceAmount());
                    order.setCreateTime(DateUtils.getNowDate());
                    order.setOrderCode(Seq.getId());
                    order.setUserId(contract.getAuserId());
                    order.setUserType("雇主");
                    order.setPayStatus("01");
                    order.setCreateBy("系统生成");
                    baseOrderMapper.insertBaseOrder(order);
                }
                if("02".equals(contract.getSignType())){
                    BaseOrder order=new BaseOrder();
                    order.setContractCode(contract.getContractCode());
                    order.setTitle("签单费");
                    order.setCompanyId(contract.getCcompanyId());
                    order.setCompanyName(contract.getCcompanyName());
                    order.setContractCode(contract.getContractCode());
                    order.setOrderAmount(contract.getSignAmount());
                    order.setCreateTime(DateUtils.getNowDate());
                    order.setOrderCode(Seq.getId());
                    order.setUserId(contract.getAuserId());
                    order.setUserType("雇主");
                    order.setPayStatus("01");
                    order.setCreateBy("系统生成");
                    baseOrderMapper.insertBaseOrder(order);
                }
            }
            //月嫂协议三方
            else if("04".equals(contract.getCategoryType())){
                //甲方支付月嫂服务费
                BaseOrder order=new BaseOrder();
                order.setContractCode(contract.getContractCode());
                order.setTitle("月嫂服务费");
                order.setCompanyId(contract.getCcompanyId());
                order.setCompanyName(contract.getCcompanyName());
                order.setContractCode(contract.getContractCode());
                order.setOrderAmount(contract.getServiceAmount());
                order.setCreateTime(DateUtils.getNowDate());
                order.setOrderCode(Seq.getId());
                order.setUserId(contract.getAuserId());
                order.setUserType("雇主");
                order.setPayStatus("01");
                order.setCreateBy("系统生成");
                baseOrderMapper.insertBaseOrder(order);
                //甲方向丙方支付履约保证金
                BaseOrder depositOrderA=new BaseOrder();
                depositOrderA.setContractCode(contract.getContractCode());
                depositOrderA.setTitle("甲方支付履约保证金");
                depositOrderA.setCompanyId(contract.getCcompanyId());
                depositOrderA.setCompanyName(contract.getCcompanyName());
                depositOrderA.setContractCode(contract.getContractCode());
                depositOrderA.setOrderAmount(contract.getDepositAmount());
                depositOrderA.setCreateTime(DateUtils.getNowDate());
                depositOrderA.setOrderCode(Seq.getId());
                depositOrderA.setUserId(contract.getAuserId());
                depositOrderA.setUserType("雇主");
                depositOrderA.setPayStatus("01");
                depositOrderA.setCreateBy("系统生成");
                baseOrderMapper.insertBaseOrder(depositOrderA);
                //已方向丙方支付履约保证金
                BaseOrder depositOrderB=new BaseOrder();
                depositOrderB.setContractCode(contract.getContractCode());
                depositOrderB.setTitle("已方支付履约保证金");
                depositOrderB.setCompanyId(contract.getCcompanyId());
                depositOrderB.setCompanyName(contract.getCcompanyName());
                depositOrderB.setContractCode(contract.getContractCode());
                depositOrderB.setOrderAmount(contract.getDepositAmount());
                depositOrderB.setCreateTime(DateUtils.getNowDate());
                depositOrderB.setOrderCode(Seq.getId());
                depositOrderB.setUserId(contract.getBuserId());
                depositOrderB.setUserType("阿姨");
                depositOrderB.setPayStatus("01");
                depositOrderB.setCreateBy("系统生成");
                baseOrderMapper.insertBaseOrder(depositOrderB);

            }*/
            //合同生效后给阿姨送积分
            BaseUser bUser=userService.selectBaseUserByUserId(contract.getBuserId());
            BaseScoreConfig signReward= baseScoreConfigService.selectBaseScoreConfigById(3L);
            bUser.setScoreAmount(bUser.getScoreAmount()+signReward.getRewardAmount());
            userService.updateBaseUserScore(bUser);

            ScoreHistory refHis=new ScoreHistory();
            refHis.setUserId(bUser.getUserId());
            refHis.setUserName(bUser.getUserName());
            refHis.setRemark("签约赠送积分");
            refHis.setScore(new BigDecimal(signReward.getRewardAmount()));
            refHis.setCreateTime(DateUtils.getNowDate());
            scoreHistoryService.insertScoreHistory(refHis);
            baseContractLogService.saveContractLogs(baseContract.getId(),currentUser.getUserId(),"确认签字",currentUser.getUserName());
        }
        catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
        finally {
            return AjaxResult.success("操作成功");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult auntSignBaseContract(BaseContract baseContract, BaseUser userInfo) {
        BaseContract contract=this.selectBaseContractById(baseContract.getId());
        if(!"02".equals(contract.getStatus())){
            return AjaxResult.error("合同状态异常");
        }
        if(contract.getBuserId().intValue()!=userInfo.getUserId().intValue()){
            return AjaxResult.error("您不是乙方用户");
        }

        baseContract.setBsignatureDate(DateUtils.getNowDate());
        baseContract.setUpdateBy(userInfo.getUserName());
        if("01".equals(contract.getCategoryType()) || "03".equals(contract.getCategoryType())){
            baseContract.setStatus("04");
        }
        else {
            baseContract.setStatus("03");
        }
        int result= this.updateBaseContract(baseContract);
        if("04".equals(baseContract.getStatus()) && !"01".equals(contract.getCategoryType()) && !"03".equals(contract.getCategoryType())){
            //合同生效后给阿姨送积分
            BaseUser bUser=userService.selectBaseUserByUserId(contract.getBuserId());
            BaseScoreConfig signReward= baseScoreConfigService.selectBaseScoreConfigById(3L);
            bUser.setScoreAmount(bUser.getScoreAmount()+signReward.getRewardAmount());
            userService.updateBaseUserScore(bUser);

            ScoreHistory refHis=new ScoreHistory();
            refHis.setUserId(bUser.getUserId());
            refHis.setUserName(bUser.getUserName());
            refHis.setRemark("签约赠送积分");
            refHis.setScore(new BigDecimal(signReward.getRewardAmount()));
            refHis.setCreateTime(DateUtils.getNowDate());
            scoreHistoryService.insertScoreHistory(refHis);
        }
        baseContractLogService.saveContractLogs(baseContract.getId(),userInfo.getUserId(),"阿姨签字",userInfo.getUserName());
        if(result>0){
            return  AjaxResult.success("操作成功");
        }else{
           return  AjaxResult.error("操作失败");
        }
    }

    @Override
    public List selectAgencyContractList(BaseContract contract) {
        if(StringUtils.isNotEmpty(contract.getStatus())){
            String status="'"+contract.getStatus().replaceAll(",","','")+"'";
            contract.setStatus(status);
        }else{
            String status="''";
            contract.setStatus(status);
        }
        return baseContractMapper.selectAgencyContractList(contract);
    }

    @Override
    public List<BaseContract> selectContractListByDate(String dateStr) {
        return baseContractMapper.selectContractListByDate(dateStr);
    }

    /**
     * 查询合同管理列表
     *
     * @param baseContract 合同管理
     * @return 合同管理
     */
    @Override
    public List<BaseContract> selectBaseContractList(BaseContract baseContract)
    {
        return baseContractMapper.selectBaseContractList(baseContract);
    }

    /**
     * 新增合同管理
     *
     * @param baseContract 合同管理
     * @return 结果
     */
    @Override
    public int insertBaseContract(BaseContract baseContract)
    {
        baseContract.setCreateTime(DateUtils.getNowDate());
        return baseContractMapper.insertBaseContract(baseContract);
    }

    /**
     * 修改合同管理
     *
     * @param baseContract 合同管理
     * @return 结果
     */
    @Override
    public int updateBaseContract(BaseContract baseContract)
    {
        baseContract.setUpdateTime(DateUtils.getNowDate());
        return baseContractMapper.updateBaseContract(baseContract);
    }

    /**
     * 批量删除合同管理
     *
     * @param ids 需要删除的合同管理主键
     * @return 结果
     */
    @Override
    public int deleteBaseContractByIds(Long[] ids)
    {
        return baseContractMapper.deleteBaseContractByIds(ids);
    }

    /**
     * 删除合同管理信息
     *
     * @param id 合同管理主键
     * @return 结果
     */
    @Override
    public int deleteBaseContractById(Long id)
    {
        return baseContractMapper.deleteBaseContractById(id);
    }

    @Override
    public List selectUserContractList(BaseContract contract) {
        if(StringUtils.isNotEmpty(contract.getStatus())){
            String status="'"+contract.getStatus().replaceAll(",","','")+"'";
            contract.setStatus(status);
        }else{
            contract.setStatus(null);
        }
        return baseContractMapper.selectUserContractList(contract);
    }

    @Override
    public List selectCompanyContractList(BaseContract baseContract) {
        if(StringUtils.isNotEmpty(baseContract.getStatus())){
            String status="'"+baseContract.getStatus().replaceAll(",","','")+"'";
            baseContract.setStatus(status);
        }else{
            String status="''";
            baseContract.setStatus(status);
        }
        return baseContractMapper.selectCompanyContractList(baseContract);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void autoCreatePayorder() {
        List<BaseContract> contractList= baseContractMapper.selectEffectContractList();

        contractList.stream().forEach(contract->{
            BaseOrder order=new BaseOrder();
            order.setContractCode(contract.getContractCode());
            List<BaseOrder> orderList= baseOrderMapper.selectBaseOrderList(order);
            String endDate=DateUtils.parseDateToStr("yyyy-MM",DateUtils.getNowDate())+"-"+(contract.getServicePayDate()<10?"0"+contract.getServicePayDate():contract.getServicePayDate());
            String startTime=DateUtils.parseDateToStr("yyyy-MM-dd",DateUtils.addDays(DateUtils.parseDate(endDate),-3))+" 00:00:00";
            String endTime=DateUtils.parseDateToStr("yyyy-MM-dd",DateUtils.parseDate(endDate))+" 23:59:59";
            BaseOrder query=orderList.stream().filter(o->o.getCreateTime().getTime()>=DateUtils.parseDate(startTime).getTime() && o.getCreateTime().getTime()<=DateUtils.parseDate(endTime).getTime() ).findFirst().orElse(null);
            if(query==null) {
                order.setTitle("服务费");
                order.setContractCode(contract.getContractCode());
                order.setOrderAmount(contract.getServiceAmount());
                order.setCreateTime(DateUtils.getNowDate());
                order.setOrderCode(Seq.getId());
                order.setUserId(contract.getAuserId());
                order.setUserType("雇主");
                order.setPayStatus("01");
                order.setCreateBy("系统生成");
                baseOrderMapper.insertBaseOrder(order);
            }
        });
    }
}
